<template>
  <div class="RecruiterLayout">
    <!-- 标题 -->
    <!--招聘者管理-->
<!--    <Title>-->
<!--      <template #default>{{ title }}</template>-->
<!--    </Title>-->
    <!-- 内容区 -->
    <section class="contentLayout">
      <el-card>
        <div class="nav">
          <el-button icon="Plus" type="primary" @click="openFormVisible('新建',false)">新建</el-button>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="刷新"
              placement="top"
          >
           <el-button :type="'text'" @click="Refresh"><el-icon size="19"><RefreshRight/></el-icon></el-button>
          </el-tooltip>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="密度"
              placement="top"
          >
            <el-dropdown placement="bottom-start" trigger="click" size='large'>
              <el-button type="text"><el-icon size="18"><Sort/></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu >
                  <el-dropdown-item
                      @click="changeSize('紧凑')"
                      :style="{backgroundColor:active1===true ?'#E6F7FF' : ''}">
                    紧凑
                  </el-dropdown-item>
                  <el-dropdown-item
                      @click="changeSize('默认')"
                      :style="{backgroundColor:active2===true ?'#E6F7FF' : ''}">
                    默认
                  </el-dropdown-item>
                  <el-dropdown-item
                      @click="changeSize('疏松')"
                      :style="{backgroundColor:active3===true ?'#E6F7FF' : ''}">
                    疏松
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-tooltip>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="列设置"
              placement="top"
          >
            <el-button type="text"><el-icon size="18"><Setting/></el-icon></el-button>
          </el-tooltip>
        </div>
        <!-- 新建/编辑弹窗 -->
        <el-dialog
            class="dialogFormVisible"
            v-model="dialogFormVisible"
            :title="dialogTitle"
            width="640"
            :before-close="handleClose">
          <el-form :model="addBoss" ref="FormRef" :rules="rules" label-position="top" :label-width="formLabelWidth " >
            <el-form-item prop="username" label="用户名" style="margin-top: 20px" clearable>
              <el-input
                  v-model="addBoss.username"
                  autocomplete="off"
                  clearable
                  placeholder="请输入用户名"  />
            </el-form-item>
            <el-form-item :class="[dialogTitle==='添加招聘者' ? '': 'display']" prop="password" label="密码" >
              <el-input
                  v-model="addBoss.password"
                  autocomplete="off"
                  placeholder="请输入密码"
                  type="password"
                  show-password  />
            </el-form-item>
            <el-form-item prop="mobile" label="电话号码" clearable >
              <el-input
                  v-model="addBoss.mobile"
                  autocomplete="off"
                  clearable
                  placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item prop="company_id" label="所属分行" >
              <el-select v-model="addBoss.company_id" placeholder="请选择所属分行" clearable>
                <el-option label="中信银行重庆分行" value="BLCDJ1QG" />
                <el-option label="中信银行陕西分行" value="DTBAFH88" />
                <el-option label="中信银行福建分行" value="FDII2D5I" />
                <el-option label="中信银行北京分行" value="FDK26OTS" />
                <el-option label="中信银行上海分行" value="IJBE1P93" />
                <el-option label="中信银行湖南分行" value="K6LR9BR6" />
                <el-option label="中信银行石家庄分行" value="P4KNVEU3" />
                <el-option label="中信银行广州分行" value="QKH0CED8"/>
                <el-option label="中信银行天津分行" value="5T80RDJB" />
              </el-select>
            </el-form-item>
            <el-form-item class="inputWidth" prop="role_id" label="账号角色" >
              <el-select v-model="addBoss.role_id" placeholder="请选择账号角色"  clearable >
                <el-option label="分行招聘者" :value="1" />
                <el-option label="分行管理员" :value="2" />
                <el-option label="总行管理员" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item class="inputWidth" prop="enable_status" label="账号状态" style="margin-left: 50px" >
              <el-select
                  v-model="addBoss.enable_status"
                  placeholder="请选择账号状态"
                  clearable
              >
<!--                <template #label>-->
<!--                  <span v-if="addBoss.enable_status===1">{{`启用`}} </span>-->
<!--                </template>-->
                <el-option label="禁用" :value="0" />
                <el-option label="启用" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item prop="avatar" label="账号头像">
              <el-upload
                  class="avatar-uploader"
                  action="#"
                  list-type="picture-card"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handleAvatarChange"
                  :multiple="false"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                  <span class="imgText">上传图片</span>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
          <template #footer style="border-bottom: 1px solid #f0f0f0">
            <div class="dialog-footer">
              <el-button @click="cancel">取消</el-button>
              <el-button v-if="dialogTitle==='添加招聘者'" type="primary" @click="submitForm(FormRef,'新建')">
                确定
              </el-button>
              <el-button v-if="dialogTitle==='编辑招聘者'" type="primary" @click="submitForm(FormRef,'编辑')">
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>

          <el-table :data="recruiter.list" :size="tableSize" v-loading="loading"  style="width: 100%" >
            <el-table-column label="序号" prop="" type="index" min-width="50px" align="center"  />
            <el-table-column label="用户名" prop="username" min-width="80px" align="center" />
            <el-table-column label="头像" prop="" min-width="60px" align="center">
<!--              方式二:使用element-plus中的自带的preview-src-list功能实现图片预览-->
              <template #default="{ row }">
                <el-button text type="primary">
                  <el-image
                      style="width: 32px; height: 25px"
                      :preview-teleported="true"
                      :src="row.avatar_url"
                      :zoom-rate="1.2"
                      :max-scale="7"
                      :min-scale="0.2"
                      :preview-src-list="[row.avatar_url]"
                      fit="cover"
                      hide-on-click-modal
                      z-index="999"
                  >
                  </el-image>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="电话号码"  prop="mobile" min-width="85px" align="center" />
            <el-table-column label="角色"  prop="" min-width="75px" align="center" >
              <template #default="scope">
                <span v-if="scope.row.role_id===1">分行招聘者</span>
                <span v-if="scope.row.role_id===2">分行管理员</span>
                <span v-if="scope.row.role_id===3">总行管理员</span>
              </template>
            </el-table-column>
            <el-table-column label="所属分行"  prop="" min-width="100px" align="center">
              <template #default="{row}">
                <span v-if="row.company_id && row.company">{{row.company.name}}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="帐号状态" prop="" min-width="60px" align="center">
              <template #default="{row}">
                <el-button v-if="row.enable_status===1" class="EnableBtn" size="small">启用</el-button>
                <el-button v-if="row.enable_status===0" class="BanBtn" size="small">禁用</el-button>
<!--                  <span>{{scope.row.enable_status===1 ? '启用' : '禁用'}}</span>-->
              </template>
            </el-table-column>
            <el-table-column label="注册时间"  prop="" min-width="100px" align="center">
              <template #default="scope">
                <span style="font-size: 14px">{{$filters.formatDate(scope.row.created_at)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="70px" align="center">
              <template #default="{row}">
                <span @click="openFormVisible('编辑',row)" class="Edit">编辑</span>
                <span @click="handleDelete(row)" class="Delete">删除</span>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <div class="demo-pagination-block">
            <div class="pageText" style="float: left;margin: 5px 15px">
              第 {{AllPages.per_page*AllPages.page-14}} -
              <span v-if="AllPages.per_page*AllPages.page<=AllPages.total">{{AllPages.page*AllPages.per_page}}</span>
              <span v-else>{{AllPages.total}}</span>
              条/总共 {{ AllPages.total }} 条
            </div>
            <el-pagination
                :current-page="AllPages.page"
                :page-size="AllPages.per_page"
                :pager-count="3"
                background
                layout="prev, pager, next"
                :total="AllPages.total"
                size="small"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                style="margin-top: 3px"
            />
          </div>
      </el-card>
    </section>
  </div>
</template>
<script setup>
import {reactive,ref,computed} from "vue";
import {Recruiter,AddBoss,UpdateBoss,DeleteBoss,UploadBoss} from "@/network/Recruiter";
import { useRouter, useRoute } from "vue-router";
import {ElMessage, ElMessageBox} from 'element-plus'
// import {Plus, RefreshRight, Setting, Sort} from '@element-plus/icons-vue'
const router = useRouter();
const route = useRoute();
const title = route.meta.title;
//图片根地址
const Url = ref('https://recruit.aicase.xyz')
//招聘者数据
const recruiter=ref({
  list:[],
  total:0
})
//获取分页
const AllPages=reactive({
  page:1,
  per_page:15,
  total:0
})
//loading区域加载
const loading = ref(true)

//获取所有招聘者信息
const AllRecruiterList = () => {
  Recruiter(AllPages).then((res)=>{
    // console.log(res.data,'res')
    //招聘者数据
    const {list,total}=res.data.data
    recruiter.value.list=list
    recruiter.value.total=total
    AllPages.total=res.data.meta.total
    if (res.data.code===0){
      setTimeout(()=>{
        loading.value=false
      },600)
    }else {
      loading.value=true
    }
  })
}
AllRecruiterList()
//新增
const addBoss=ref({
  username:'',//用户名
  password:'',//密码
  mobile:'', //手机号
  company_id:'',//所属分行
  enable_status:1,//状态
  role_id:'',//账号角色
  avatar:''//图像
})
const addBoss1={...addBoss.value}
//所属分行及分行id
const companyID=([
  {id:'BLCDJ1QG',name:'中信银行重庆分行'},
  {id:'DTBAFH88',name:'中信银行陕西分行'},
  {id:'FDII2D5I',name:'中信银行福建分行'},
  {id:'FDK26OTS',name:'中信银行北京分行'},
  {id:'IJBE1P93',name:'中信银行上海分行'},
  {id:'K6LR9BR6',name:'中信银行湖南分行'},
  {id:'P4KNVEU3',name:'中信银行石家庄分行'},
  {id:'QKH0CED8',name:'中信银行广州分行'},
  {id:'5T80RDJB',name:'中信银行天津分行'},
  {id:"976G1Q9A",name:'中信银行天津分行'},
])

// 控制弹窗显示
const dialogFormVisible = ref(false);
// 弹窗标题
const dialogTitle = ref("");
//表单行宽
const formLabelWidth = '140px'

//表单校验
const FormRef=ref()
//密码校验
const validatePassword=(rule,value,callback)=>{
  //不能为空
  if(value ===''){
    callback(new Error('密码是必填项'))
  }else {
    const reg=/^[a-zA-Z0-9_-]{6,12}$/
    reg.test(value) ? callback() : callback(new Error('密码格式不对，需要6到12位字符，请确认格式'))
  }
}
//手机号校验
const validateMobile=(rule,value,callback)=>{
  //不能为空
  if (value===''){
    callback(new Error('用户名是必填项'))
  }else {
    const PhoneNumber=/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    PhoneNumber.test(value) ? callback() : callback(new Error('手机号格式不对，请输入正确的手机号'))
  }
}
//表单校验规则
const rules=reactive({
  username:[{ required: true, message: '请输入用户名', trigger: 'change' }],
  password:[{validator:validatePassword,trigger:'change',required: true}],
  mobile:[{validator:validateMobile,trigger:'change',required: true}],
  company_id:[{required: true, trigger: 'change',message: '请选择所属分行' }],
  role_id:[{ required: true, message: '请选择账号角色', trigger: 'change' }],
  enable_status:[{ required: true, trigger: 'change',message: '请选择账号状态'}],
  avatar:[{ required: true, trigger: 'change',message: '请上传头像'}]
})

//新建功能头像部分
const imageUrl = ref(null)
const upload = ref()

//图片上传
const handleAvatarChange = async (
    uploadFile
) => {
  const types = ['image/webp', 'image/jpeg', 'image/jpg', 'image/png'];
  if (!types.includes(uploadFile.raw.type)) {
    ElMessage.error('图片格式只能是JPEG、JPG、PNG、WEBP!')
    return false
  } else if (Math.floor(uploadFile.size / 1024 / 1024) >= 5 || Math.ceil(uploadFile.size / 1024) <= 10) {
    ElMessage.error('图片大小只能是10KB到5MB之间!')
    return false
  } else {
    upload.value = uploadFile.raw
    const fileData = new FormData();
    fileData.append('file', upload.value)
    await UploadBoss(fileData).then((res) => {
          // console.log(res, 'up')
          addBoss.value.avatar = res.data.data.full_url
          imageUrl.value = addBoss.value.avatar
        }, (err) => {
          console.log(err);
    })
  }
}
//当为编辑时对数据储存
const selectedRow=ref()
// 打开新建/编辑弹窗
const openFormVisible=(type,row)=>{
  dialogFormVisible.value=true
  if (type==='新建'){
    dialogTitle.value='添加招聘者'
    imageUrl.value=null
    if (FormRef.value){
      addBoss.value=addBoss1
      FormRef.value.resetFields();
    }

  }else if (type==='编辑' && row){
    dialogTitle.value='编辑招聘者'
    //将选中行数据赋值给addBoss
    addBoss.value={...row}
    //记录当前行数据
    selectedRow.value=row

    //图片
    addBoss.value.avatar=row.avatar_url
    imageUrl.value=addBoss.value.avatar
    //分行判断
    if (row.company_id && row.company){
      addBoss.value.company_id=row.company.name
    }else {
      addBoss.value.company_id=''
    }
  }
}

// 提交表单数据
const submitForm = async (formEl,type) => {
  if (type==='新建'){
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
          AddBoss(addBoss.value).then((data)=>{
            if (data.data.code ===0) {
              dialogFormVisible.value = false;
              AllRecruiterList()
              ElMessage({
                showClose: true,
                message: "添加成功",
                type: "success",
              });
            }else {
              dialogFormVisible.value = false;
              ElMessage({
                showClose: true,
                message: data.data.message,
                type: "error",
              });
            }
            console.log(data,'dt')
          })
          // console.log('submit!',addBoss.value)
      } else {
        console.log('error submit!', fields)
      }
    })
  }else if (type==='编辑'){
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        const row= {...selectedRow.value}
       UpdateBoss(addBoss.value,row.id).then((data)=>{
         if (data.data.code===0){
           dialogFormVisible.value = false;
           AllRecruiterList()
           ElMessage({
             showClose: true,
             message: "编辑成功",
             type: "success",
           });
         }else {
           dialogFormVisible.value = false;
           ElMessage({
             showClose: true,
             message: data.data.message,
             type: "error",
           });
         }
         console.log(data,'updata')
       })
        // console.log('submit!',addBoss.value)
      } else {
        console.log('error submit!', fields)
      }
    })
  }
}
const cancel = () => {
  dialogFormVisible.value=false
  // if (FormRef.value){
  //   FormRef.value.resetFields();
  // }
}
//弹窗右上角小x关闭并重置表单清除校验
const handleClose = () => {
  dialogFormVisible.value=false
  // if (FormRef.value){
  //   FormRef.value.resetFields();
  // }
}
//删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '你确定要删除记录吗?',
      '删除记录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        //用户点击确认
        const result=await DeleteBoss(row.id)
        ElMessage.success(result.data.message ? result.data.message :'删除成功')
        AllRecruiterList()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
const handleCurrentChange = (val) => {
  AllPages.page=val
  loading.value=true
  AllRecruiterList()
}
//page-size 改变时触发
const handleSizeChange = (val) => {
  AllPages.per_page=val
  AllPages.page=1
  loading.value=true
  AllRecruiterList()
}

//刷新
const Refresh= () => {
  loading.value=true
  AllRecruiterList()
}
//密度
const tableSize=ref('default')
const active1=ref(false)
const active2=ref(true)
const active3=ref(false)
const changeSize = (size) => {
  if (size==='紧凑'){
    tableSize.value='small'
    active1.value=true
    active2.value=false
    active3.value=false
  }else if (size==='默认'){
    tableSize.value='default'
    active1.value=false
    active2.value=true
    active3.value=false
  }else if (size==='疏松'){
    tableSize.value='large'
    active1.value=false
    active2.value=false
    active3.value=true
  }else {
    tableSize.value='default'
    active1.value=false
    active2.value=true
    active3.value=false
  }
}
//AddBoss 和 UpdateBoss 的请求未处理网络错误

</script>

<style scoped lang="scss">
.display{
  display: none;
}
.RecruiterLayout{
  .contentLayout{
    /*头部样式*/
    .nav{
      height: 50px;
      float: right;
      /*刷新、密度、列设置样式*/
      :deep(.el-button--text){
        color: #1F1F1F;
        margin: 0 5px;
      }
      :deep(.el-button--text:hover){
        color:#409EFF;
      }
    }
    /*el-dialog部分样式*/
    /*头部字体及下划线*/
    :deep(.el-dialog__header){
      border-bottom: 1px solid var(--color-border);
    }
    :deep(.el-dialog__title){
      font-size: 16px;
      color: var(--color-text);
      font-weight: 500;
      line-height: 22px;
      padding: 5px 5px;
    }
    /*账号角色及状态输入框样式*/
    :deep(.inputWidth){
      width: 250px;
      float: left;
    }
    /*el-upload图片上传样式*/
    .avatar-uploader .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
    /*底部footer样式*/
    :deep(.el-dialog__footer){
      display: block;
      border-top: 1px solid var(--color-border);
      margin-top: 30px;
      line-height: 30px;
    }
    /*table表头部分固定死样式*/
    //.tableTitle{
    //  width: 1052px;
    //  height: 50px;
    //  border-bottom: 1px solid var(--color-border);
    //  background-color: var(--color-background-2);
    //  display: flex;
    //  justify-content: space-around;
    //  align-items: center;
    //  padding-left: 15px;
    //  padding-right: 20px;
    //  line-height: 50px;
    //}
    /*el-table部分样式*/
    /*table表头*/
    :deep(.el-table){
      font-weight: normal;
      color: var(--color-text);
    }
    :deep(.el-table .el-table__header th){
      background-color:var(--color-background-2);
      font-weight: normal;
      color: var(--color-text);
    }
    :deep(.el-table .el-table__header th>.cell){
      border-right: 1px solid #0000000f;
    }
    :deep(.el-table .el-table__header th:last-child>.cell){
      border-right: none;
    }
    :deep(.cell){
     line-height: 30px;
    }
    /*账号状态样式*/
    .EnableBtn,.BanBtn{
      cursor: text;
    }
    :deep(.EnableBtn){
      color: #389e0d;
      background: #f6ffed;
      border-color: #b7eb8f;
    }
    :deep(.BanBtn){
      color: #cf1322;
      background: #fff1f0;
      border-color: #ffa39e;
    }
    /*编辑和删除按钮*/
    .Edit,.Delete{
      cursor: pointer;
      color:#1890ff;
      padding:0 5px ;
    }
    /*分页组件*/
    .demo-pagination-block{
      height: 50px;
      float: right;
      padding-top: 10px;
    }
  }
}

</style>
/*el-upload图片上传样式*/
<style>
.avatar-uploader .el-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  position: relative;
  font-size: 20px;
  color: currentcolor;
  width: 100px;
  height: 100px;
  text-align: center;
  padding-bottom: 10px;
  .imgText{
    font-size: 14px;
    font-style:normal;
    position: absolute;
    left: 25%;
    top:60%;
  }
}
</style>
